//
//  TLMainViewController.swift
//  TLiOS26LiquidGlassDemo
//
//  Created by jiayin on 2025/7/11.
//

import UIKit

class TLMainViewController: UIViewController {

    private let cellReuseIdentifier = "TLMainTableViewCellIdentifier"
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.isPagingEnabled = true
        tableView.separatorStyle = .singleLine
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(TLMainTableViewCell.self, forCellReuseIdentifier: "TLMainTableViewCellIdentifier")
        return tableView
    }()

    let mainModels: [TLMainModel] = [
        TLMainModel(title: "Observable Object", details: "去体验"),
        TLMainModel(title: "Update Properties", details: "去体验"),
        TLMainModel(title: "iPadOS Menu Bar", details: "去体验"),
        TLMainModel(title: "通知中心", details: "去体验"),
        TLMainModel(title: "UINavigationController", details: "去体验"),
        TLMainModel(title: "SF Symbols 7", details: "去体验"),
        TLMainModel(title: "UITabBarController", details: "去体验"),
        TLMainModel(title: "动画选项flushUpdates", details: "去体验"),
        TLMainModel(title: "圆角UICornerConfiguration", details: "去体验"),
        TLMainModel(title: "动画效果drawOn与drawOff", details: "去体验"),
        TLMainModel(title: "动画效果UIVisualEffectView", details: "去体验"),
        TLMainModel(title: "UIButton新功能", details: "去体验"),
        TLMainModel(title: "UIViewController新功能", details: "去体验"),
        TLMainModel(title: "动态切换图标", details: "去体验"),
        TLMainModel(title: "UISlider", details: "去体验"),
        TLMainModel(title: "UIColor新增功能", details: "去体验"),
    ];
    
    private let viewControllerTypes: [Int: UIViewController.Type] = [
        0: TLObservableObjectViewController.self,
        1: TLUpdatePropertiesViewController.self,
        2: TLPadOSMenuViewController.self,
        3: TLNotificationCenterViewController.self,
        4: TLUINavigationViewController.self,
        5: TLSFSymbols7ViewController.self,
        6: TLTabBarViewController.self,
        7: TLAnimatorViewController.self,
        8: TLViewCornerConfigViewController.self,
        9: TLImageViewController.self,
        10: TLVisualEffectViewController.self,
        11: TLButtonViewController.self,
        12: TLTransformSceneViewController.self,
        13: TLAppIconViewController.self,
        14: TLUISliderViewController.self,
        15: TLColorViewController.self,
        // 添加一个默认键来处理未知的行索引
        Int.max: UIViewController.self
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .systemBackground
        title = "iOS 26"
        setupTableView()
        // 监听系统外观变化
        if #available(iOS 13.0, *) {
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(updateAppearance),
                name: UIScene.didActivateNotification,
                object: nil
            )
        }
    }
    
    private func setupTableView() {
        view.addSubview(tableView)
        tableView.backgroundColor = .systemBackground
        
        // 约束设置（假设使用自动布局）
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }

    @objc private func updateAppearance() {
        view.backgroundColor = .systemBackground
        tableView.backgroundColor = .systemBackground
        tableView.reloadData()
    }

    deinit {
        if #available(iOS 13.0, *) {
            NotificationCenter.default.removeObserver(
                self,
                name: UIScene.didActivateNotification,
                object: nil
            )
        }
    }
}

extension TLMainViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mainModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as? TLMainTableViewCell else {
                return UITableViewCell()
            }
            cell.model = mainModels[indexPath.row]
        return cell
    }
    
    // 设置cell的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return TLMainTableViewCell.height(for: mainModels[indexPath.row])
    }
    
}

extension TLMainViewController: UITableViewDelegate {
    // 实现必要的代理方法，如果需要的话
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if let viewControllerType = viewControllerTypes[indexPath.row] {
            let viewController = viewControllerType.init()
            viewController.title = mainModels[indexPath.row].title
            
            // 确保有一个导航控制器来推送视图控制器
            if let navigationController = self.navigationController {
                navigationController.pushViewController(viewController, animated: true)
            } else {
                // 处理没有导航控制器的情况，例如显示一个警告或弹出新的导航控制器
                let navigationController = UINavigationController(rootViewController: viewController)
                self.present(navigationController, animated: true, completion: nil)
            }
        } else {
            // 处理字典中未找到对应控制器类型的情况
            let viewController = UIViewController()
            // 可以选择显示一个错误消息或执行其他操作
            self.present(UINavigationController(rootViewController: viewController), animated: true, completion: nil)
        }
    }
}
